import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Row, Col, Tooltip } from 'antd';
import { connect } from 'dva';
import _ from 'lodash';
import debounce from 'lodash/debounce';
import React, { PureComponent } from 'react';

import BasicInfo from './basicInfo'; // 基础信息
import constant from './constant';
import InBankBondInfoC from './InBankBondInfoC'; //
import style from './index.less';
import PositionC from './Position'; // 持仓信息

import { FirstHeaderC, SecondHeaderC, PrimaryC, PrimaryGhostC, ModalC, TableC, InputC, IconC } from '../../../../comps';
import { uniqueKey, AutomaticSettlement } from '../../../../utils/commonFunc';

@Form.create()
class InterBank extends PureComponent {
  constructor() {
    super();
    this.state = {
      direct: undefined, // 委托方向
      trustee: undefined, // 托管机构
      portfolio: undefined, // 组合
      currentUser: {}, // 当前登录用户信息
      positionArr: [], // 持仓信息
      confirmQuerys: {}, // 二次确认数据
      isShow: false, // 是否显示二次确认弹窗
      trailColumns: [], // 试算结果列表
      trailDataSource: [], // 试算结果数据
      trailModel: false, // 试算模态框
      productCode: undefined, // 产品code
      portfolioCode: undefined, // 组合code
      productGroupId: undefined, // 产品组id
      uid: '',
    };
    // 搜索框加防抖
    this.searchOnChange = debounce(this.searchOnChange, 500);
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'interBankBasicInfoM/getUserInfo',
      payload: localStorage.getItem('antd-pro-userId'), // 获取对当前用户信息
      callback: (res) => {
        this.setState({
          currentUser: res,
        });
      },
    });
    const uid = uniqueKey();
    uid.then((r) => {
      this.setState({ uid: r });
    });
  }

  showBtn = () => {
    const { type, loading } = this.props;
    if (type == '1' || type == '2' || type == 10 || type == 11 || type == 12) {
      let url = '';
      // eslint-disable-next-line default-case
      switch (type) {
        // 指令
        case 1 || '1':
          url = 'interBankBasicInfoM/SaveInstruction';
          break;
        // 簿记
        case 2 || '2':
          url = 'interBankBasicInfoM/SaveInstructionw2';
          break;
        // 存续管理
        case 10 || '10':
          url = 'interBankBasicInfoM/tradeBookSave';
          break;
        // 组合试算
        case 11 || '11':
          url = 'portfolioTrialAddM/interBankSave';
          break;
        // 多基金
        case 12 || '12':
          url = 'moreFundsOrderM/bondAdd';
          break;
      }
      return (
        <div style={{ float: 'right' }}>
          {/* {type == "2" && <PrimaryC
            loading={loading.effects['trailM/trialData'] === true}
            onClick={() => this.trialOnClick()}
            title={'试算'}
            style={{ marginRight: "10px" }}
          />} */}
          <PrimaryC onClick={() => this.handleOnClick()} title={type == '1' ? '下达' : '确定'} loading={loading.effects[url] == true} />
          <PrimaryGhostC onClick={() => this.onCancle()} title='取消' style={{ marginLeft: '10px' }} />
        </div>
      );
    }
    if (type == '4') {
      return (
        <div style={{ float: 'right' }}>
          <PrimaryC onClick={() => this.handleOnClick()} title='交收' loading={loading.effects['interBankBasicInfoM/getTradeInstruction'] == true} />
          <PrimaryGhostC onClick={() => this.onCancle()} title='取消' style={{ marginLeft: '10px' }} />
        </div>
      );
    }
  };

  // 二次确认取消按钮 关闭模态框
  handleCancel = () => {
    this.setState({
      isShow: false,
      confirmQuerys: {},
    });
  };

  // 二次确认modal框
  showModal = () => {
    const { confirmQuerys, isShow } = this.state;
    const { loading } = this.props;
    const modalProps = {
      visible: isShow,
      title: '确认指令下达',
      width: 1100,
      height: 1000,
      className: 'confirmOrder',
      confirmLoading: loading.effects['interBankBasicInfoM/SaveInstruction'] === true,
    };
    return (
      <ModalC {...modalProps} onOk={this.handleOnClick} onCancel={this.handleCancel}>
        <BasicInfo type='3' infoData={confirmQuerys} />
      </ModalC>
    );
  };

  // 点击下达或确定
  handleOnClick = () => {
    const { type, dispatch, currentAsset } = this.props;
    const { currentUser, uid } = this.state;
    if (type == '1' || type == '2' || type == 10 || type == 11 || type == 12) {
      //  新增指令和簿记时执行
      const datas = this.basicInfo.getInfo();
      const datas1 = this.bondInfo.getData();

      if (datas !== undefined && datas1 !== undefined) {
        //  基础信息和质押券信息不为undefined继续执行
        const formData = _.cloneDeep(datas);
        const newForm = formData;
        newForm.firstSettlementDate = formData.firstSettlementDate.format('YYYYMMDD');
        newForm.settlementDate = formData.settlementDate.format('YYYYMMDD');
        newForm.zgPledgeVo = datas1.list;
        const query = {}; // 最终发给后态的数据
        query.type = 4;
        query.method = type == '1' || type == 10 ? null : '0';
        query.portfolioId = type == 12 ? null : this.state.portfolio;
        query.productGroupId = type == 12 ? this.state.productGroupId : null;
        query.userId = currentUser.userId;
        query.userName = currentUser.name;
        query.trade4 = newForm;
        query.uid = uid;
        let isFlag = true; //  校验融资回购总计金额受否不超过T+0，或T+1可用
        // 如果选择融资回购
        if (this.state.direct === '2') {
          const { buybackCode, zgPledgeVo } = query.trade4;
          // 如果选的不是买断式 并且 没填质押券 提示
          if (!constant.some((v) => v.value == buybackCode) && !zgPledgeVo) {
            message.warning('质押券信息不能为空');
            return;
          }
        }
        if (type == 10) {
          dispatch({
            type: 'interBankBasicInfoM/tradeBookSave',
            payload: query,
            callback: () => {
              this.basicInfo.setForm(); //  成功后清空基础信息，持仓信息，质押券信息
              this.bondInfo.setTable();
              this.props.onOk();
              this.setState({
                direct: undefined, // 委托方向
                trustee: undefined, // 托管机构
                portfolio: undefined, // 组合
              });
            },
          });
          return;
        }
        if (newForm.orderSide == '1') {
          // eslint-disable-next-line no-shadow
          const datas = newForm.settlementSpeed == '1' ? currentAsset.t0 : currentAsset.t1; // 根据清算速度选择对比t0/t1可用
          if (datas1.total > datas) {
            // 若融券回购时总计金额大于对应t0/t1可用则不做任何操作，并提示
            isFlag = false;
          }
        }
        if (type == '1' && isFlag) {
          if (this.state.isShow) {
            // 下达指令
            dispatch({
              type: 'interBankBasicInfoM/SaveInstruction',
              payload: query,
              callback: () => {
                this.basicInfo.setForm();
                this.bondInfo.setTable();
                //  成功后清空基础信息，持仓信息，质押券信息
                // this.props.onOk(); // 告知父组件操作成功
                this.setState({
                  direct: undefined, // 委托方向
                  trustee: undefined, // 托管机构
                  portfolio: undefined, // 组合
                  confirmQuerys: {},
                  isShow: false,
                });
                // eslint-disable-next-line no-shadow
                const uid = uniqueKey();
                uid.then((r) => {
                  this.setState({ uid: r });
                });
              },
            });
          } else {
            this.setState({
              confirmQuerys: { ...query },
              isShow: true,
            });
          }
        } else if (type == '2' && isFlag) {
          // 判断租户是否配置自动交收，若配置自动交收给予弹窗提醒
          if (
            AutomaticSettlement(type, 'interBankBasicInfoM/SaveInstructionw2', query, dispatch, () => {
              this.basicInfo.setForm(); //  成功后清空基础信息，持仓信息，质押券信息
              this.bondInfo.setTable();
              this.props.onOk();
              this.setState({
                direct: undefined, // 委托方向
                trustee: undefined, // 托管机构
                portfolio: undefined, // 组合
              });
              // eslint-disable-next-line no-shadow
              const uid = uniqueKey();
              uid.then((r) => {
                this.setState({ uid: r });
              });
            })
          )
            return;

          dispatch({
            type: 'interBankBasicInfoM/SaveInstructionw2',
            payload: query,
            callback: () => {
              this.basicInfo.setForm(); //  成功后清空基础信息，持仓信息，质押券信息
              this.bondInfo.setTable();
              this.props.onOk();
              this.setState({
                direct: undefined, // 委托方向
                trustee: undefined, // 托管机构
                portfolio: undefined, // 组合
              });
              // eslint-disable-next-line no-shadow
              const uid = uniqueKey();
              uid.then((r) => {
                this.setState({ uid: r });
              });
            },
          });
        } else if (type == '11' && isFlag) {
          dispatch({
            type: 'portfolioTrialAddM/interBankSave',
            payload: query,
            callback: () => {
              this.basicInfo.setForm(); //  成功后清空基础信息，持仓信息，质押券信息
              this.bondInfo.setTable();
              this.props.onOk();
              this.setState({
                direct: undefined, // 委托方向
                trustee: undefined, // 托管机构
                portfolio: undefined, // 组合
              });
              // eslint-disable-next-line no-shadow
              const uid = uniqueKey();
              uid.then((r) => {
                this.setState({ uid: r });
              });
            },
          });
        } else if (type == 12 && isFlag) {
          dispatch({
            type: 'moreFundsOrderM/bondAdd',
            payload: query,
            callback: (res) => {
              if (res) {
                this.basicInfo.setForm(); //  成功后清空基础信息，持仓信息，质押券信息
                this.bondInfo.setTable();
                this.props.onOk();
                this.setState({
                  direct: undefined, // 委托方向
                  trustee: undefined, // 托管机构
                  portfolio: undefined, // 组合
                });
              }
              // eslint-disable-next-line no-shadow
              const uid = uniqueKey();
              uid.then((r) => {
                this.setState({ uid: r });
              });
            },
          });
        } else {
          const str = newForm.settlementSpeed == '1' ? 'T+0' : 'T+1';
          message.warning(`成交金额总计不可超过${str}可用数量`);
        }
      }
    } else if (type == '4') {
      // 簿记交收时执行
      const { info } = this.props;
      dispatch({
        type: 'interBankBasicInfoM/getTradeInstruction',
        payload: { id: info.id },
        callback: () => {
          this.props.onOk();
        },
      });
    }
  };

  // 点击取消
  onCancle = () => {
    const { type } = this.props;
    if (type == '1' || type == '2' || type == '11' || type == 12) {
      // 新增指令&簿记
      this.basicInfo.setForm(); // 清空基础信息
      this.basicInfo.setState({
        buyBackMoney: undefined,
        buyBackRate: undefined,
        occupationDays: undefined,
      });
      this.bondInfo.setTable(); // 清空质押券信息
      this.position.setPosition(); // 清空持仓信息
      if (type == '2' || type == 11 || type == 12) this.props.onCancel();
      this.setState({
        direct: undefined, // 委托方向
        trustee: undefined, // 托管机构
        portfolio: undefined, // 组合
        confirmQuerys: {},
        isShow: false,
      });
    } else if (type == '3') {
      // 簿记详情
    } else if (type == '4' || type == '10') {
      this.props.onCancel(); // 簿记交收点击取消
    }
  };

  // 托管机构change事件
  trusteeOnChange = (e) => {
    if (e) {
      this.setState({
        trustee: e,
      });
    } else {
      this.setState({ trustee: undefined });
    }
  };

  // 持仓信息刷新数据事件
  onChanges = (e) => {
    this.setState({
      positionArr: e,
    });
  };

  // 组合change事件
  portfolioOnChange = (e) => {
    if (e !== undefined) {
      this.setState({ portfolio: e.key });
      this.props.onChange(e.key);
    } else {
      this.setState({ portfolio: undefined });
      this.props.onChange(undefined);
    }
  };

  // 委托方向改变事件
  directOnChange = (e) => {
    if (e) {
      this.setState({
        direct: e,
      });
    } else {
      this.setState({
        direct: undefined,
      });
    }
  };

  // 系列产品
  seriesProductsOnChange = (e) => {
    if (e !== undefined) {
      this.setState({ portfolio: e });
      this.props.onChange(e);
    } else {
      this.setState({ portfolio: undefined });
      this.props.onChange(undefined);
    }
  };

  // 产品组变更
  productGroupOnChange = (e) => {
    if (e !== undefined) {
      this.setState({ productGroupId: e.key });
      this.props.productGroupOnChange(e.key);
    } else {
      this.setState({ productGroupId: undefined });
      this.props.productGroupOnChange(undefined);
    }
  };

  // 获取组合code
  portfolioCode = (e) => {
    if (e) {
      this.setState({ portfolioCode: e });
    } else this.setState({ portfolioCode: undefined });
  };

  // 获取产品code
  productCode = (e) => {
    if (e) {
      this.setState({ productCode: e });
    } else this.setState({ productCode: undefined });
  };

  changeFee = (data, price) => {
    this.basicInfo?.changeFee('pledgedbondsamount', data || undefined);
    setTimeout(() => {
      this.basicInfo?.changeFee('price', price || undefined);
    }, 100);
  };

  // 持仓双击点击事件
  addNewPledgeBond = (record) => {
    this.bondInfo.addNewPledgeBond(record);
  };

  // 持仓信息搜索框右侧按钮
  rightContent = () => (
    <div className='flotRight'>
      <div>
        <Tooltip placement='top' title='查询'>
          {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
          <div className='btnPlus' onClick={this.searchPosition} style={{ cursor: 'pointer' }}>
            <IconC type='search' />
          </div>
        </Tooltip>
      </div>
    </div>
  );

  // 响应搜索
  searchPosition = () => {
    const {
      form: { getFieldValue },
    } = this.props;
    const searchData = getFieldValue('search');
    this.position?.searchPosition(searchData);
  };

  // 响应搜索框变化
  searchOnChange = (e) => {
    this.position?.searchPosition(e);
  };

  // 清空持仓信息搜索框
  resetSearch = () => {
    const {
      form: { setFieldsValue },
    } = this.props;
    setFieldsValue({ search: null });
  };

  changeBuybackCode = (e) => {
    if (e) {
      if (constant.map((v) => v.value).includes(e)) {
        this.bondInfo.setBuybackCodeRule(false);
      }
    }
  };

  // 根据type值展示不同业务的组件
  showComponent = () => {
    const { type, info, listId } = this.props;
    const { portfolio, trustee, direct, productGroupId } = this.state;
    // 质押权信息是否可编辑
    const isDisabled = (portfolio == undefined && productGroupId == undefined) || direct == undefined || trustee == undefined;
    // 持仓信息是否展示
    const positionIsShow = trustee == undefined || (portfolio == undefined && productGroupId == undefined);

    if (type == '1' || type == '2' || type == '11' || type == '12') {
      return (
        <>
          <Row>
            <Col span={24}>
              <div style={{ position: 'relative' }}>
                <FirstHeaderC title='持仓信息' />
                {trustee != undefined && (portfolio != undefined || productGroupId != undefined) && (
                  <div
                    style={{
                      position: 'absolute',
                      top: '-10px',
                      right: 0,
                      width: '220px',
                    }}
                  >
                    <InputC
                      form={this.props.form}
                      dataIndex='search'
                      placeholder='请输入代码或简称进行搜索'
                      suffix={this.rightContent()}
                      onChange={(e) => this.searchOnChange(e.target?.value)}
                    />
                  </div>
                )}
                <PositionC
                  onChange={this.onChanges}
                  onRef={(ref) => (this.position = ref)}
                  portfolio={portfolio}
                  productGroupId={productGroupId}
                  direct={direct}
                  trustee={trustee}
                  type={type}
                  addNewPledgeBond={this.addNewPledgeBond}
                  positionIsShow={positionIsShow}
                  resetSearch={this.resetSearch}
                />
              </div>
            </Col>
          </Row>
          <Row style={{ marginTop: '10px' }}>
            <Col span={24}>
              <FirstHeaderC title='交易要素' />
              <div style={{ marginTop: '10px', position: 'relative' }}>
                <SecondHeaderC title='质押券信息' />
                <div style={{ position: 'absolute', top: '-10px', right: 0 }}>
                  <PrimaryC title='新增' disabled={isDisabled} onClick={this.bondInfo?.handleClick} />
                </div>
                <div>
                  <InBankBondInfoC
                    onRef={(ref) => (this.bondInfo = ref)}
                    portfolio={this.state.portfolio}
                    direct={this.state.direct}
                    trustee={this.state.trustee}
                    isDisabled={isDisabled}
                    positionArr={this.state.positionArr}
                    productGroupId={productGroupId}
                    type={type}
                    account={(e) => this.basicInfo.changeAccount(e)}
                    changeFee={this.changeFee}
                  />
                </div>
                <div style={{ marginTop: '20px' }}>
                  <SecondHeaderC title='基本信息' />
                  <BasicInfo
                    onRef={(ref) => (this.basicInfo = ref)}
                    trusteeOnChange={this.trusteeOnChange} // 托管机构
                    portfolioOnChange={this.portfolioOnChange} // 组合改变事件
                    directOnChange={this.directOnChange} // 委托方向
                    productGroupOnChange={this.productGroupOnChange}
                    type={type}
                    portfolioCode={this.portfolioCode}
                    productCode={this.productCode}
                    changeBuybackCode={this.changeBuybackCode}
                  />
                </div>
              </div>
            </Col>
          </Row>
          <div className={style.btn} style={{ marginTop: '10px', height: '50px' }}>
            {this.showBtn()}
          </div>
        </>
      );
    }
    if (type == '4' || type == '3' || type == 10) {
      // 交收&&详情
      return (
        <div style={{ marginTop: '10px', position: 'relative' }}>
          <SecondHeaderC title='质押券信息' />
          {type == 10 ? (
            <div style={{ position: 'absolute', top: '-10px', right: 0 }}>
              <PrimaryC title='新增' disabled={isDisabled} onClick={this.bondInfo?.handleClick} />
            </div>
          ) : null}
          <div>
            <InBankBondInfoC
              type={type}
              direct={type == 10 ? (this.state.direct ? '1' : undefined) : this.state.direct} // 交易录入时质押券都展示融券回购的场景
              onRef={(ref) => (this.bondInfo = ref)}
              portfolio={this.state.portfolio}
              trustee={this.state.trustee}
              positionArr={this.state.positionArr}
              infoData={info}
              account={(e) => this.basicInfo?.changeAccount(e)}
              changeFee={this.changeFee}
            />
          </div>
          <div style={{ marginTop: '20px' }}>
            <SecondHeaderC title='基本信息' />
          </div>
          <BasicInfo
            onRef={(ref) => (this.basicInfo = ref)}
            trusteeOnChange={this.trusteeOnChange} // 托管机构
            portfolioOnChange={this.portfolioOnChange} // 组合改变事件
            directOnChange={this.directOnChange} // 委托方向
            seriesProductsOnChange={(e) => {
              this.seriesProductsOnChange(e);
            }}
            portfolioCode={this.portfolioCode}
            productCode={this.productCode}
            type={type}
            infoData={info}
            listId={listId}
            changeBuybackCode={this.changeBuybackCode}
          />
          <div className={style.btn} style={{ marginTop: '10px', height: '50px' }}>
            {this.showBtn()}
          </div>
        </div>
      );
    }
  };

  // 试算按钮点击
  // eslint-disable-next-line react/no-unused-class-component-methods
  trialOnClick = () => {
    const { type, dispatch, currentAsset } = this.props;
    const { currentUser, productCode, portfolioCode } = this.state;
    const datas = this.basicInfo.getInfo();
    const datas1 = this.bondInfo.getData();
    if (datas !== undefined && datas1 !== undefined) {
      //  基础信息和质押券信息不为undefined继续执行
      const formData = _.cloneDeep(datas);
      const newForm = formData;
      newForm.firstSettlementDate = formData.firstSettlementDate.format('YYYYMMDD');
      newForm.settlementDate = formData.settlementDate.format('YYYYMMDD');
      newForm.zgPledgeVo = datas1.list;
      const query = {}; // 最终发给后态的数据
      query.type = 4;
      query.method = type == '1' || type == 10 ? null : '0';
      query.portfolioId = this.state.portfolio;
      query.userId = currentUser.userId;
      query.userName = currentUser.name;
      query.trade4 = newForm;
      query.productCode = productCode; // 产品code
      query.portfolioCode = portfolioCode; // 组合code
      query.tenant = currentUser.tenant; // 租户code
      query.businessType = '4';
      let isFlag = true; //  校验融资回购总计金额受否不超过T+0，或T+1可用
      if (newForm.orderSide == '1') {
        // eslint-disable-next-line no-shadow
        const datas = newForm.settlementSpeed == '1' ? currentAsset.t0 : currentAsset.t1; // 根据清算速度选择对比t0/t1可用
        if (datas1.total > datas) {
          // 若融券回购时总计金额大于对应t0/t1可用则不做任何操作，并提示
          isFlag = false;
        }
      }
      if (isFlag) {
        this.setState({ trailModel: true }, () => {
          dispatch({
            type: 'trailM/trialData',
            payload: query,
            callback: (res) => {
              if (res) {
                this.setState({
                  trailColumns: res.columns,
                  trailDataSource: res.dataSource,
                });
              } else {
                this.setState({
                  trailColumns: [],
                  trailDataSource: [],
                });
              }
            },
          });
        });
      }
    }
  };

  // 试算结果列表优化
  trailColumnsChange = (data) => {
    if (data) {
      data?.map((item) => {
        if (item.key == 'ruleDesc') {
          item.ellipsis = true;
        } else {
          item.width = '125px';
        }
      });
    }
    return data;
  };

  // 试算结果
  showTrail = () => {
    const { trailModel, trailColumns, trailDataSource } = this.state;
    const newTrailColumns = this.trailColumnsChange(trailColumns);
    return (
      <ModalC
        visible={trailModel}
        title='试算结果'
        width={1200}
        onOk={() => {
          this.setState({ trailModel: false });
        }}
        onCancel={() => {
          this.setState({ trailModel: false });
        }}
      >
        <TableC
          columns={newTrailColumns}
          dataSource={trailDataSource}
          loading={this.props.loading.effects['trailM/trialData'] === true}
          scroll={{ y: '231px' }}
          rowKey='id'
          hidePage
        />
      </ModalC>
    );
  };

  render() {
    return (
      <div style={{ marginTop: '20px' }}>
        {this.showComponent()}
        {this.state.isShow ? this.showModal() : null}
        {this.state.trailModel && this.showTrail()}
      </div>
    );
  }
}
export default connect(({ attributionAnalysisM, portfolioTrialAddM, loading, trailM, moreFundsOrderM }) => ({
  attributionAnalysisM,
  portfolioTrialAddM,
  loading,
  trailM,
  moreFundsOrderM,
}))(InterBank);
